import requests
import cairosvg
import pytesseract
import re

# 获取HTML内容
url = "https://katastar.rgz.gov.rs/eKatastarPublic/FindParcela.aspx?KoID=715913"  # 替换为实际的URL
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

response = requests.get(url, headers=headers)
html_content=response.text


from PIL import Image

# 提取SVG部分
from bs4 import BeautifulSoup
with open('html_content.txt', 'w', encoding='utf-8') as file:  # 使用 'w' 模式表示写入，并覆盖原有内容
      file.write(html_content)
soup = BeautifulSoup(html_content, 'html.parser')

# 提取隐藏参数
viewstate = soup.find('input', {'id': '__VIEWSTATE'}).get('value')
viewstategenerator = soup.find('input', {'id': '__VIEWSTATEGENERATOR'}).get('value')
eventvalidation = soup.find('input', {'id': '__EVENTVALIDATION'}).get('value')

print("VIEWSTATE:", viewstate)
print("VIEWSTATEGENERATOR:", viewstategenerator)
print("EVENTVALIDATION:", eventvalidation)

# 查找并移除 stroke="silver" 的 <g> 标签
for g in soup.find_all('g', attrs={'stroke': 'silver'}):
    g.decompose()
svg_element = soup.find('svg')  # 假设SVG是直接嵌入在HTML中的
svg_content = str(svg_element)

# 手动移除命名空间
svg_content = svg_content.replace('xmlns="http://www.w3.org/2000/svg "', '')

print(svg_content)
# 尝试转换为 PNG
try:
    png_data = cairosvg.svg2png(bytestring=svg_content)
    with open('captcha.png', 'wb') as f:
        f.write(png_data)
    print("验证码已保存为 captcha.png")
    # 打开保存的验证码图片
    image = Image.open('captcha.png')

    # 使用 pytesseract 提取文字
    text = pytesseract.image_to_string(image)

    # 移除换行符和多余空格
    cleaned_text = text.replace('\n', '').replace('\r', '').strip()

    # 移除非字母数字字符
    cleaned_text = re.sub(r'[^a-zA-Z0-9]', '', cleaned_text)

    print("提取的文字内容：")
    print(cleaned_text)
    print("提取的文字长度：")
    print(len(cleaned_text))


    form_data = {
        '__VIEWSTATE': viewstate,
        '__VIEWSTATEGENERATOR': viewstategenerator,
        '__EVENTVALIDATION': eventvalidation,
        # 添加其他表单字段
        'ctl00$ContentPlaceHolder1$txtBrParcele': '5198',  # 示例：输入验证码
        'ctl00$ContentPlaceHolder1$SVGCaptchaControl$CaptchaText':cleaned_text,
        '__ASYNCPOST':"true",
        'ctl00$ContentPlaceHolder1$ctl00':'ctl00$ContentPlaceHolder1$UpdatePanel1|ctl00$ContentPlaceHolder1$btnSubmit',
        'ctl00$ContentPlaceHolder1$btnSubmit': 'Прикажи'  # 示例：提交按钮
    }

    cookies = response.cookies
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    # 发送 POST 请求https://katastar.rgz.gov.rs/eKatastarPublic/FindParcelaResult.aspx
    response = requests.post(url, data=form_data, cookies=cookies, headers=headers)
        # 打印响应内容
    print(response.text)
    # 将响应内容写入到文本文件
    with open('response.txt', 'w', encoding='utf-8') as file:  # 使用 'w' 模式表示写入，并覆盖原有内容
        file.write(response.text)
        
    # 打开一个文件用于保存详细信息
    with open("response_details.txt", "w", encoding="utf-8") as file:
        # 写入请求信息
        file.write("请求方法: {}\n".format(response.request.method))
        file.write("请求URL: {}\n".format(response.request.url))
        file.write("请求头: {}\n".format(response.request.headers))
        file.write("请求体: {}\n".format(response.request.body))

        # 写入响应信息
        file.write("\n响应状态码: {}\n".format(response.status_code))
        file.write("响应URL: {}\n".format(response.url))
        file.write("响应头: {}\n".format(response.headers))

        # 写入跳转历史
        file.write("\n跳转历史:\n")
        for resp in response.history:
            file.write("跳转前的URL: {}\n".format(resp.url))
            file.write("跳转前的状态码: {}\n".format(resp.status_code))
            file.write("跳转前的响应头: {}\n".format(resp.headers))
            file.write("跳转前的响应内容: \n")
            file.write(resp.text)
            file.write("\n")
    # 发送 POST 请求
    response = requests.get("https://katastar.rgz.gov.rs/eKatastarPublic/FindParcelaResult.aspx", cookies=response.cookies, headers=headers)
      # 将响应内容写入到文本文件
    with open('response2.txt', 'w', encoding='utf-8') as file:  # 使用 'w' 模式表示写入，并覆盖原有内容
        file.write(response.text)

except Exception as e:
    # 将异常信息写入到 error.log 文件中
    with open('error.log', 'a', encoding='utf-8') as file:  # 使用 'a' 模式表示追加到文件末尾
        file.write(f"转换失败: {e}\n")
    print(f"转换失败: {e}")

